//对于axios进行二次封装
import axios from 'axios'
//引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//在当前模块中引入store
import {useDetailStore, useUserStore} from '@/store'

//创建axios实例
const request = axios.create({
    //基础路径
    baseURL: 'http://gmall-h5-api.atguigu.cn/api',
    //请求不能超过5S
    timeout: 5000
})

//请求拦截器
request.interceptors.request.use((config) => {
    const store_detail = useDetailStore()
    const store_user = useUserStore()
    if (store_detail.uuid_token) {
        //请求头添加一个字段 userTempId
        config.headers!.userTempId = store_detail.uuid_token
    }
    //需要携带token带给服务器
    if (store_user.token) {
        config.headers!.token = store_user.token
    }
    //进度条开始
    nprogress.start()
    return config
})

//响应拦截器
request.interceptors.response.use(
    (res) => {
        //进度条结束
        nprogress.done()
        return res.data
    },
    (error) => {
        return Promise.reject(error)
    }
)

declare module 'axios' {
    export interface AxiosResponse<T = any> extends Promise<T> {}
}

export default request
